package com.devplatform.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.devplatform.pojo.Ads;
import com.devplatform.pojo.Advertisers;
import com.devplatform.pojo.dto.AdsDetailDto;
import com.devplatform.pojo.dto.DetailedAdvertisers;
import com.devplatform.pojo.validateInt.UpdateGroup;
import com.devplatform.pojo.vo.DataVo;
import com.devplatform.service.AdsService;
import com.devplatform.service.AdvertisersService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


@Slf4j
@RestController
@RequestMapping("/api/ads")
@RequiredArgsConstructor
public class AdManagementSystem {

    private final AdsService adsService;
    private final AdvertisersService advertisersService;

    //查看所有广告
    @GetMapping
    public DataVo getAllAd(
            @RequestParam(defaultValue = "1") Integer currentPage,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer adStatus
    ) {
        IPage<AdsDetailDto> adsIPage = new Page<>(currentPage, pageSize);
        QueryWrapper<AdsDetailDto> queryWrapper = new QueryWrapper<>();

        queryWrapper.ne("ad_status", 6);

        //按名称搜索
        if (StringUtils.hasText(name)) {
            queryWrapper.like("name", name);
        }

        if (adStatus != null) {
            queryWrapper.eq("ad_status", adStatus);
        }

        List<AdsDetailDto> result = adsService.getAllAds(adsIPage, queryWrapper);
        Map<String, Object> data = new HashMap<>();
        data.put("list", result);
        data.put("total", adsIPage.getTotal());
        data.put("currentPage", adsIPage.getCurrent());
        data.put("pageSize", adsIPage.getSize());

        return DataVo.ok(data);
    }

    // 获取信息流活跃广告
    @GetMapping("/homeAds")
    public DataVo getHomeAds() {
        try {
            QueryWrapper<Ads> queryWrapper = new QueryWrapper<>();
            // 首页广告条件：状态为使用中，广告类型为首页广告，且在有效期内
            queryWrapper.eq("ad_status", 2)
                    .eq("ad_type", 1)
                    .le("start_time", LocalDateTime.now())
                    .ge("end_time", LocalDateTime.now());

            List<Ads> homeAds = adsService.list(queryWrapper);
            return DataVo.ok(homeAds);
        } catch (Exception e) {
            return DataVo.error("获取首页广告失败");
        }
    }

    //获取侧边栏广告
    @GetMapping("/loggedAds")
    public DataVo getLoggedAds() {
        try {
            QueryWrapper<Ads> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ad_status", 2)
                    .eq("ad_type", 2)
                    .le("start_time", LocalDateTime.now())
                    .ge("end_time", LocalDateTime.now());

            List<Ads> loggedAds = adsService.list(queryWrapper);
            return DataVo.ok(loggedAds);
        } catch (Exception e) {
            return DataVo.error("获取登录广告失败");
        }
    }



    //添加广告
    @PostMapping("/createAd")
    public DataVo<Object> addAd(@RequestBody @Valid Ads ads) {
        ads.setSubmitTime(LocalDateTime.now());
        boolean ad = adsService.save(ads);
        return ad ? DataVo.ok(ads) : DataVo.error("添加广告失败!");
    }

    //通过广告
    @PostMapping("/approveAd")
    public DataVo approveAd(@RequestBody @Valid Ads ads) {
        Integer id = ads.getId();
        if (id == null) {
            return DataVo.error("id不存在!");
        }
        Ads updateAd = new Ads();
        updateAd.setId(id);
        updateAd.setAdStatus(2);
        updateAd.setSubmitTime(LocalDateTime.now());

        boolean success = adsService.updateById(updateAd);
        if (success) {
            return DataVo.ok("广告审核通过成功");
        } else {
            return DataVo.error("广告审核通过失败");
        }

    }

    //驳回广告
    @PostMapping("/rejectAd")
    public DataVo rejectAd(@RequestBody @Valid Ads ads) {
        Integer id = ads.getId();
        if (id == null) {
            return DataVo.error("id不存在!");
        }

        // 验证驳回原因
        if (ads.getRejectReason() == null || ads.getRejectReason().trim().isEmpty()) {
            return DataVo.error("驳回原因不能为空!");
        }

        Ads updateAd = new Ads();
        updateAd.setId(id);
        updateAd.setAdStatus(4);
        updateAd.setDescription("已驳回");
        updateAd.setRejectReason(ads.getRejectReason());
        updateAd.setSubmitTime(LocalDateTime.now());
        boolean success = adsService.updateById(updateAd);
        if (success) {
            return DataVo.ok("广告已驳回");
        } else {
            return DataVo.error("广告驳回失败!");
        }
    }

    //删除广告
    @DeleteMapping
    public DataVo<String> deleteAd(@RequestParam @NotNull Integer id) {
        Ads ad = new Ads();
        ad.setId(id);
        ad.setAdStatus(6);
        boolean result = adsService.updateById(ad);
        return result ? DataVo.ok("删除成功!") : DataVo.error("删除失败!");
    }

    //多选删除

    //修改广告
    @PostMapping("/updateAd")
    public DataVo<Object> updateAd(@RequestBody @Valid Ads ads) {
        Integer id = ads.getId();
        if (id == null) {
            return DataVo.error("修改失败!id不存在");
        }
        boolean save = adsService.updateById(ads);
        return save ? DataVo.ok(ads.getId()) : DataVo.error("修改失败!");
    }

    //查看所有广告商
    @GetMapping("/advertiser")
    public DataVo getAllAdvertisers(
            @RequestParam(defaultValue = "1") Integer currentPage,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer status
    ) {
        IPage<DetailedAdvertisers> advertisersIPage = new Page<>(currentPage, pageSize);
        QueryWrapper<DetailedAdvertisers> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("status", 3);
        //按名称搜索
        if (StringUtils.hasText(name)) {
            queryWrapper.like("name", name);
        }
        // 按状态过滤
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        List<DetailedAdvertisers> save = advertisersService.getAllAdvertisers(advertisersIPage, queryWrapper);
        Map<String, Object> data = new HashMap<>();
        data.put("list", save);
        data.put("total", advertisersIPage.getTotal());
        data.put("currentPage", advertisersIPage.getCurrent());
        data.put("pageSize", advertisersIPage.getSize());
        return DataVo.ok(data);
    }

    //添加广告商
    @PostMapping("/advertiser")
    public DataVo addAdvertiser(@RequestBody @Valid Advertisers advertisers) {
        boolean save = advertisersService.save(advertisers);
        return save ? DataVo.ok() : DataVo.error();
    }

    //删除广告商(逻辑删除)
    @DeleteMapping("/advertiser")
    public DataVo deleteAdvertiser(@RequestParam @NotNull Integer id) {
        Advertisers advertisers = new Advertisers();
        advertisers.setId(id);
        advertisers.setStatus(3);
        boolean save = advertisersService.updateById(advertisers);
        return save ? DataVo.ok("删除成功!") : DataVo.error("删除失败!广告商不存在");
    }

    //修改广告商
    @PutMapping("/advertiser")
    public DataVo updateAdvertiser(@RequestBody @Valid @Validated(UpdateGroup.class) Advertisers advertiser) {
        boolean save = advertisersService.updateById(advertiser);
        return save ? DataVo.ok("修改成功") : DataVo.error("修改失败!");
    }

    //禁用广告商
    @PostMapping("/disableAdvertiser")
    public DataVo disableAdvertiser(
            @RequestParam @NotNull Integer id,
            @RequestParam(defaultValue = "2") Integer status
    ) {
        Advertisers updateAdvertiser = new Advertisers();
        updateAdvertiser.setId(id);
        updateAdvertiser.setStatus(status);

        boolean save = advertisersService.updateById(updateAdvertiser);

        if (save && status == 2) {
            QueryWrapper<Ads> adsQueryWrapper = new QueryWrapper<>();
            adsQueryWrapper.eq("advertiser_id", id);

            List<Ads> advertiserAds = adsService.list(adsQueryWrapper);
            for (Ads ad : advertiserAds) {
                Ads updateAd = new Ads();
                updateAd.setId(ad.getId());
                updateAd.setAdStatus(5); // 已封禁状态
                adsService.updateById(updateAd);
            }
        } else if (status == 1) {
            QueryWrapper<Ads> adsQueryWrapper = new QueryWrapper<>();
            adsQueryWrapper.eq("advertiser_id", id);
            adsQueryWrapper.eq("ad_status", 5); // 只处理已封禁的广告

            List<Ads> bannedAds = adsService.list(adsQueryWrapper);
            for (Ads ad : bannedAds) {
                Ads updateAd = new Ads();
                updateAd.setId(ad.getId());
                updateAd.setAdStatus(2); // 恢复为已通过状态
                adsService.updateById(updateAd);
            }
        }
        return save ? DataVo.ok("操作成功!") : DataVo.error("操作失败!");
    }


    // 广告数据统计
    @GetMapping("/getAdStatistics")
    public DataVo getAdStatistics(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String position
    ) {
        try {
            //查询最近7天
            if (!StringUtils.hasText(startDate) || !StringUtils.hasText(endDate)) {
                LocalDate end = LocalDate.now();
                LocalDate start = end.minusDays(6);
                startDate = start.format(DateTimeFormatter.ISO_LOCAL_DATE);
                endDate = end.format(DateTimeFormatter.ISO_LOCAL_DATE);
            }
            // 构建查询条件
            QueryWrapper<Ads> queryWrapper = new QueryWrapper<>();
            // 排除已删除的广告
            queryWrapper.ne("ad_status", 6);

            // 位置过滤
            if (StringUtils.hasText(position)) {
                queryWrapper.eq("position", position);
            }

            // 时间范围过滤
            if (StringUtils.hasText(startDate) && StringUtils.hasText(endDate)) {
                LocalDateTime start = LocalDateTime.parse(startDate + "T00:00:00");
                LocalDateTime end = LocalDateTime.parse(endDate + "T23:59:59");

                // 查询在时间范围内有效的广告
                queryWrapper.le("start_time", end).ge("end_time", start);
            }

            // 获取符合条件的广告列表
            List<Ads> adsList = adsService.list(queryWrapper);

            // 计算基础统计数据
            long totalImpressions = 0;
            long totalClicks = 0;
            int activeAdsCount = 0;

            for (Ads ad : adsList) {
                Integer impressions = ad.getImpressions() != null ? ad.getImpressions() : 0;
                Integer clicks = ad.getClicks() != null ? ad.getClicks() : 0;

                totalImpressions += impressions;
                totalClicks += clicks;

                // 统计活跃广告（状态为使用中且在有效期内的广告）
                if (ad.getAdStatus() == 2 &&
                        ad.getStartTime() != null &&
                        ad.getEndTime() != null &&
                        LocalDateTime.now().isAfter(ad.getStartTime()) &&
                        LocalDateTime.now().isBefore(ad.getEndTime())) {
                    activeAdsCount++;
                }
            }

            // 计算平均点击率
            double avgCtr = totalImpressions > 0 ? (double) totalClicks / totalImpressions * 100 : 0;

            // 获取对比期数据计算趋势（比如对比上一个周期）
            Map<String, Object> previousStats = getPreviousPeriodStats(startDate, endDate, position);
            long previousImpressions = (Long) previousStats.get("totalImpressions");
            long previousClicks = (Long) previousStats.get("totalClicks");
            double previousCtr = (Double) previousStats.get("avgCtr");
            int previousActiveAds = (Integer) previousStats.get("activeAdsCount");

            // 计算趋势百分比
            double impressionsTrend = previousImpressions > 0 ?
                    (double) (totalImpressions - previousImpressions) / previousImpressions * 100 : 0;
            double clicksTrend = previousClicks > 0 ?
                    (double) (totalClicks - previousClicks) / previousClicks * 100 : 0;
            double ctrTrend = previousCtr > 0 ?
                    (avgCtr - previousCtr) / previousCtr * 100 : 0;
            double activeAdsTrend = previousActiveAds > 0 ?
                    (double) (activeAdsCount - previousActiveAds) / previousActiveAds * 100 : 0;

            // 构建图表数据
            Map<String, Object> chartData = generateChartData(startDate, endDate, position);

            // 构建广告详情列表
            List<Map<String, Object>> adDetails = new ArrayList<>();
            for (Ads ad : adsList) {
                Integer impressions = ad.getImpressions() != null ? ad.getImpressions() : 0;
                Integer clicks = ad.getClicks() != null ? ad.getClicks() : 0;
                double ctr = impressions > 0 ? (double) clicks / impressions * 100 : 0;

                Map<String, Object> detail = new HashMap<>();
                detail.put("id", ad.getId());
                detail.put("name", ad.getName());
                detail.put("type", ad.getAdType());
                detail.put("adTypeDescription", getAdTypeDescription(ad.getAdType()));
                detail.put("position", ad.getPosition());
                detail.put("impressions", impressions);
                detail.put("clicks", clicks);
                detail.put("ctr", String.format("%.2f", ctr));
                adDetails.add(detail);
            }

            // 返回完整统计数据
            Map<String, Object> statsData = new HashMap<>();
            statsData.put("totalImpressions", totalImpressions);
            statsData.put("totalClicks", totalClicks);
            statsData.put("avgCtr", Double.parseDouble(String.format("%.2f", avgCtr)));
            statsData.put("activeAdsCount", activeAdsCount);
            statsData.put("impressionsTrend", Double.parseDouble(String.format("%.1f", impressionsTrend)));
            statsData.put("clicksTrend", Double.parseDouble(String.format("%.1f", clicksTrend)));
            statsData.put("ctrTrend", Double.parseDouble(String.format("%.1f", ctrTrend)));
            statsData.put("activeAdsTrend", Double.parseDouble(String.format("%.1f", activeAdsTrend)));
            statsData.put("chartData", chartData);
            statsData.put("adDetails", adDetails);

            return DataVo.ok(statsData);

        } catch (Exception e) {
            return DataVo.error("获取统计数据失败");
        }
    }

    private String getAdTypeDescription(Integer adType) {
        if (adType == null) return "未知类型";
        switch (adType) {
            case 1:
                return "信息流广告";
            case 2:
                return "侧边栏广告";
            default:
                return "未知类型";
        }
    }

    // 获取上一个周期的统计数据用于对比
    private Map<String, Object> getPreviousPeriodStats(String startDate, String endDate, String position) {
        Map<String, Object> stats = new HashMap<>();

        try {
            // 计算上一个周期的时间范围
            if (StringUtils.hasText(startDate) && StringUtils.hasText(endDate)) {
                LocalDateTime currentStart = LocalDateTime.parse(startDate + "T00:00:00");
                LocalDateTime currentEnd = LocalDateTime.parse(endDate + "T23:59:59");

                long daysBetween = java.time.Duration.between(currentStart, currentEnd).toDays();
                LocalDateTime previousStart = currentStart.minusDays(daysBetween + 1);
                LocalDateTime previousEnd = currentStart.minusSeconds(1);

                QueryWrapper<Ads> queryWrapper = new QueryWrapper<>();
                queryWrapper.ne("ad_status", 6);

                // 基于广告有效期进行过滤
                queryWrapper.le("start_time", previousEnd).ge("end_time", previousStart);

                if (StringUtils.hasText(position)) {
                    queryWrapper.eq("position", position);
                }

                List<Ads> previousAds = adsService.list(queryWrapper);

                long totalImpressions = 0;
                long totalClicks = 0;
                int activeAdsCount = 0;

                for (Ads ad : previousAds) {
                    Integer impressions = ad.getImpressions() != null ? ad.getImpressions() : 0;
                    Integer clicks = ad.getClicks() != null ? ad.getClicks() : 0;
                    totalImpressions += impressions;
                    totalClicks += clicks;

                    if (ad.getAdStatus() == 3) {
                        activeAdsCount++;
                    }
                }

                double avgCtr = totalImpressions > 0 ? (double) totalClicks / totalImpressions * 100 : 0;

                stats.put("totalImpressions", totalImpressions);
                stats.put("totalClicks", totalClicks);
                stats.put("avgCtr", avgCtr);
                stats.put("activeAdsCount", activeAdsCount);
            }
        } catch (Exception e) {
            log.error("获取上一个周期统计数据失败:" + e.getMessage());
        }
        return stats;
    }

    // 生成图表数据
    private Map<String, Object> generateChartData(String startDate, String endDate, String position) {
        Map<String, Object> chartData = new HashMap<>();

        try {
            LocalDateTime start = LocalDateTime.parse(startDate + "T00:00:00");
            LocalDateTime end = LocalDateTime.parse(endDate + "T23:59:59");

            // 获取按日期分组的真实统计数据
            List<Map<String, Object>> dailyStats = getDailyStats(start, end, position);

            // 确保返回完整的日期范围数据
            List<String> dateLabels = new ArrayList<>();
            List<Integer> impressionData = new ArrayList<>();
            List<Integer> clickData = new ArrayList<>();
            List<Double> ctrData = new ArrayList<>();

            // 生成完整的日期标签
            LocalDate currentDate = start.toLocalDate();
            LocalDate finalEndDate = end.toLocalDate();

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd");

            while (!currentDate.isAfter(finalEndDate)) {
                String dateLabel = currentDate.format(formatter);
                dateLabels.add(dateLabel);

                // 查找对应日期的数据
                boolean found = false;
                for (Map<String, Object> daily : dailyStats) {
                    String statsDate = (String) daily.get("date");
                    if (currentDate.toString().equals(statsDate)) {
                        impressionData.add(((Number) daily.get("impressions")).intValue());
                        clickData.add(((Number) daily.get("clicks")).intValue());
                        ctrData.add(((Number) daily.get("ctr")).doubleValue());
                        found = true;
                        break;
                    }
                }

                // 如果没有找到对应日期的数据，填充0
                if (!found) {
                    impressionData.add(0);
                    clickData.add(0);
                    ctrData.add(0.0);
                }

                currentDate = currentDate.plusDays(1);
            }

            chartData.put("dateLabels", dateLabels);
            chartData.put("impressionData", impressionData);
            chartData.put("clickData", clickData);
            chartData.put("ctrData", ctrData);

        } catch (Exception e) {
            // 返回空数据
            chartData.put("dateLabels", Collections.emptyList());
            chartData.put("impressionData", Collections.emptyList());
            chartData.put("clickData", Collections.emptyList());
            chartData.put("ctrData", Collections.emptyList());
        }

        return chartData;
    }
    // 按日期获取统计数据
    private List<Map<String, Object>> getDailyStats(LocalDateTime start, LocalDateTime end, String position) {
        List<Map<String, Object>> result = new ArrayList<>();

        try {
            // 获取所有符合条件的广告
            QueryWrapper<Ads> adsQuery = new QueryWrapper<>();
            adsQuery.ne("ad_status", 6); // 排除已删除的广告

            if (StringUtils.hasText(position)) {
                adsQuery.eq("position", position);
            }

            List<Ads> adsList = adsService.list(adsQuery);

            // 按日期分组统计 - 这里需要修改为基于广告活动时间统计
            Map<String, Map<String, Long>> dailyStats = new HashMap<>();

            // 生成日期范围内的所有日期，确保包含完整的时间范围
            LocalDate currentDate = start.toLocalDate();
            LocalDate finalEndDate = end.toLocalDate();

            while (!currentDate.isAfter(finalEndDate)) {
                String dateKey = currentDate.toString();
                dailyStats.putIfAbsent(dateKey, new HashMap<>());
                dailyStats.get(dateKey).put("impressions", 0L);
                dailyStats.get(dateKey).put("clicks", 0L);
                currentDate = currentDate.plusDays(1);
            }

            // 重新统计每个广告在查询时间范围内的数据
            for (Ads ad : adsList) {

                // 检查广告是否在查询时间范围内活跃
                if (isAdActiveInPeriod(ad, start, end)) {
                    // 按比例分配数据到每一天（简化处理）
                    distributeAdStatsToDays(ad, dailyStats, start, end);
                }
            }

            // 转换为返回格式
            List<String> sortedDates = new ArrayList<>(dailyStats.keySet());
            Collections.sort(sortedDates);

            for (String date : sortedDates) {
                Map<String, Object> record = new HashMap<>();
                Map<String, Long> dayStats = dailyStats.get(date);

                Long impressions = dayStats.getOrDefault("impressions", 0L);
                Long clicks = dayStats.getOrDefault("clicks", 0L);
                double ctr = impressions > 0 ? (double) clicks / impressions * 100 : 0.0;

                record.put("date", date);
                record.put("impressions", impressions);
                record.put("clicks", clicks);
                record.put("ctr", Double.parseDouble(String.format("%.2f", ctr)));

                result.add(record);
            }
        } catch (Exception e) {
        }

        return result;
    }

    // 检查广告在时间范围内是否活跃
    private boolean isAdActiveInPeriod(Ads ad, LocalDateTime start, LocalDateTime end) {
        if (ad.getStartTime() == null || ad.getEndTime() == null) {
            return false;
        }

        // 广告开始时间在查询结束时间之前，且广告结束时间在查询开始时间之后
        return ad.getStartTime().isBefore(end) && ad.getEndTime().isAfter(start);
    }

    // 将广告统计数据分配到每一天
    private void distributeAdStatsToDays(Ads ad, Map<String, Map<String, Long>> dailyStats,
                                         LocalDateTime start, LocalDateTime end) {
        // 获取广告的总数据
        Long totalImpressions = ad.getImpressions() != null ? ad.getImpressions().longValue() : 0L;
        Long totalClicks = ad.getClicks() != null ? ad.getClicks().longValue() : 0L;

        // 计算广告在查询时间范围内的活跃天数
        LocalDate adStart = ad.getStartTime().toLocalDate();
        LocalDate adEnd = ad.getEndTime().toLocalDate();

        // 计算查询时间范围内的实际活跃天数
        LocalDate queryStart = start.toLocalDate();
        LocalDate queryEnd = end.toLocalDate();

        LocalDate effectiveStart = adStart.isAfter(queryStart) ? adStart : queryStart;
        LocalDate effectiveEnd = adEnd.isBefore(queryEnd) ? adEnd : queryEnd;

        long activeDays = java.time.temporal.ChronoUnit.DAYS.between(effectiveStart, effectiveEnd) + 1;

        if (activeDays <= 0) return;

        // 平均分配到每一天
        long dailyImpressions = totalImpressions / activeDays;
        long dailyClicks = totalClicks / activeDays;

        // 如果有余数，将余数分配到第一天
        long impressionsRemainder = totalImpressions - (dailyImpressions * activeDays);
        long clicksRemainder = totalClicks - (dailyClicks * activeDays);

        // 分配到具体的日期
        LocalDate currentDate = effectiveStart;
        int dayCount = 0;

        while (!currentDate.isAfter(effectiveEnd)) {
            String dateKey = currentDate.toString();
            Map<String, Long> dayStats = dailyStats.get(dateKey);

            if (dayStats != null) {
                long dayImpressions = dailyImpressions;
                long dayClicks = dailyClicks;

                // 第一天分配余数
                if (dayCount == 0) {
                    dayImpressions += impressionsRemainder;
                    dayClicks += clicksRemainder;
                }

                dayStats.put("impressions", dayStats.get("impressions") + dayImpressions);
                dayStats.put("clicks", dayStats.get("clicks") + dayClicks);
            }

            currentDate = currentDate.plusDays(1);
            dayCount++;
        }
    }

    // 记录广告曝光接口
    @PostMapping("/recordImpression")
    public DataVo recordImpression(@RequestBody Map<String, Object> impressionData) {
        try {
            Integer adId = (Integer) impressionData.get("adId");
            String position = (String) impressionData.get("position");

            Ads ad = adsService.getById(adId);
            if (ad != null) {
                // 更新曝光量
                Integer currentImpressions = ad.getImpressions() != null ? ad.getImpressions() : 0;
                ad.setImpressions(currentImpressions + 1);

                adsService.updateById(ad);

                return DataVo.ok("曝光记录成功");
            } else {
                return DataVo.error("广告不存在");
            }
        } catch (Exception e) {
            return DataVo.error("记录曝光失败");
        }
    }

    //点击记录接口
    @PostMapping("/recordClick")
    public DataVo recordClick(@RequestBody Map<String, Object> clickData) {
        try {
            Integer adId = (Integer) clickData.get("adId");
            String position = (String) clickData.get("position");

            Ads ad = adsService.getById(adId);
            if (ad != null) {
                // 只更新点击量
                Integer currentClicks = ad.getClicks() != null ? ad.getClicks() : 0;
                ad.setClicks(currentClicks + 1);

                adsService.updateById(ad);

                return DataVo.ok("点击记录成功");
            } else {
                return DataVo.error("广告不存在");
            }
        } catch (Exception e) {
            return DataVo.error("记录点击失败");
        }
    }
}
